package com.hg.onlineshop.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hg.onlineshop.entity.Cart;
import com.hg.onlineshop.mapper.CartMapper;
import com.hg.onlineshop.service.ICartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private ICartService cartService;

    @Autowired
    private CartMapper cartMapper;

    @GetMapping("/single/{memberId}")
    public List<Cart> findCartByMemberId(@PathVariable("memberId")Integer memberId) {
        List<Cart> carts = cartMapper.selectCartItemByMemberId(memberId);
        return carts;
    }

    @PostMapping("/save")
    public String saveCart(@RequestBody Cart cart) {
        QueryWrapper<Cart> queryWrapper = new QueryWrapper();
        queryWrapper.eq("product_id", cart.getProductId()).eq("member_id", cart.getMemberId());
        Cart queryCart = cartService.getOne(queryWrapper);
        boolean flag = false;
        if (queryCart == null) {
            flag = cartService.save(cart);
        } else {
            Integer num = queryCart.getNum();
            cart.setNum(cart.getNum() + num);
            cart.setId(queryCart.getId());
            flag = cartService.updateById(cart);
        }
        if (flag) {
            return "S";
        } else {
            return "E";
        }
    }
}
